﻿using System;
using System.Diagnostics;
using System.Linq;
using LINQPad.OpenAccess.Helpers;

namespace LINQPad.OpenAccess.Infrastructure
{
    /// <summary>
    /// Service locator facade.
    /// </summary>
    public static class ServiceLocator
    {
        [DebuggerBrowsable( DebuggerBrowsableState.Never )]
        private static IServiceLocator _CurrentInstance;
        private static readonly object _SyncRoot = new object( );

        /// <summary>
        /// Creates the default service locator.
        /// </summary>
        /// <returns>
        /// The default service locator.
        /// </returns>
        private static IServiceLocator CreateDefault( )
        {
            return new NinjectBasedServiceLocator( );
        }

        /// <summary>
        /// Gets or sets the current service locator instance.
        /// </summary>
        /// <value>
        /// The current.
        /// </value>
        /// <exception cref="System.InvalidOperationException">If no service locator is available.</exception>
        public static IServiceLocator Current
        {
            get
            {
                if ( _CurrentInstance == null )
                {
                    lock ( _SyncRoot )
                    {
                        if ( _CurrentInstance == null )
                        {
                            _CurrentInstance = CreateDefault( );
                            if ( _CurrentInstance == null )
                                throw new InvalidOperationException( "Service locator not (yet?) available !" );
                        }
                    }
                }
                return _CurrentInstance;
            }
            set
            {
                Guard.ArgumentNotNull( value, "value" );
                _CurrentInstance = value;
            }
        }
    }
}
